import resuest from './request';

/**
 * @module  公用js
 * @author xiongsha
 * @date 2021-04-15 20:36:35
 */
export default {
  replace(str1, str2) {
    const reg = new RegExp(str1);
    const result = 'dsdssdssd'.replace(reg, str2);
    console.log(result, 'res');
  },
  isValid(s) {
    // 给定一个只包括 '('，')'，'{'，'}'，'['，']'的字符串 s ，判断字符串是否有效。
    // 有效字符串需满足：
    // 左括号必须用相同类型的右括号闭合。
    // 左括号必须以正确的顺序闭合。
    const res = [];
    const obj = {
      '(': ')',
      '[': ']',
      '{': '}',
    };
    for (let i = 0; i < s.length; i++) {
      if (s.length % 2 === 1) {
        return false;
      }
      const item = s[i];
      if (item === '(' || item === '[' || item === '{') {
        res.push(item);
      } else {
        if (item !== obj[res.pop()]) {
          return false;
        }
      }
    }
    return res.length === 0;
  },
  addNum(num1, num2) {
    // 大数相加
    const maxLen = Math.max(num1.length, num2.length);
    num1 = num1.padStart(maxLen, 0);
    num2 = num2.padStart(maxLen, 0);
    let bit = '';
    let carry = 0; // 进位
    let sum = '';
    // eslint-disable-next-line for-direction
    for (let i = maxLen - 1; i >= 0; i--) {
      bit = Number(num2[i] || 0) + Number(num1[i] || 0) + carry;
      carry = Math.floor(bit / 10);
      sum = (bit % 10) + sum;
    }
    if (carry) {
      sum = carry + sum;
    }
    return sum;
  },
  debounce(fn, delay, immerate) {
    // 防抖
    let timer = null;
    let flag = true;
    return function () {
      const context = this;
      const arg = arguments;
      if (immerate) {
        if (timer) {
          clearTimeout(timer);
          timer = null;
        }
        if (flag) {
          fn.apply(context, arg);
          flag = false;
        }
        timer = setTimeout(() => {
          flag = true;
          timer = null;
        }, delay);
      } else {
        if (timer) {
          clearTimeout(timer);
          timer = null;
        }
        timer = setTimeout(() => {
          fn.apply(context, arg);
        }, delay);
      }
    };
  },
  thorttling(fn, delay, immerate) {
    // 节流
    let timer = false;
    let flag = true;
    return function () {
      if (immerate) {
        // 立即执行
        const context = this;
        const arg = arguments;
        if (flag) {
          fn.apply(context, arg);
          flag = false;
          setTimeout(() => {
            flag = true;
          }, delay);
        }
      } else {
        if (!timer) {
          timer = true;
          const context = this;
          const arg = arguments;
          setTimeout(() => {
            fn.apply(context, arg);
            timer = false;
          }, delay);
        }
      }
    };
  },
  twoQianfenwei(nums) {
    const newNums = nums.split('');
    if (newNums <= 3) {
      return newNums;
    }
    let index = 1;
    for (let i = 0; i < nums.length; i++) {
      if (i === 1) {
        newNums.splice(i + 1, 0, ',');
      }
      if (i - index === 4 && i !== nums.length) {
        index = i;
        newNums.splice(i + 1, 0, ',');
      }
    }
    return newNums.join('');
  },
  getqianfenwei(nums) {
    const newNums = nums.split('');
    if (newNums <= 3) {
      return newNums;
    }

    for (let i = 0; i < nums.length - 1; i++) {
      if (i === 0) {
        newNums.splice(i + 1, 0, ',');
      }
      if (i !== 0 && i % 4 === 0 && i < nums.length - 1) {
        newNums.splice(i + 1, 0, ',');
      }
    }
    return newNums.join('');
  },
  asyncToGenerator(generatorFunc) {
    // 利用Generator实现async
    return new Promise((reslove, reject) => {
      const gen = generatorFunc();
      function step(key, arg) {
        let genResult;
        try {
          genResult = gen[key](arg);
        } catch (error) {
          return reject(error);
        }
        const { value, done } = genResult;
        if (done) {
          return reslove(value);
        }
        return step('next', value);
      }
      step('next');
    });
  },
  jsonP(url, data) {
    return new Promise((reslove, reject) => {
      const dataString = url.indexOf('?') === -1 ? '?' : '&';
      const callBack = `CB${new Date().getTime()}`;
      url += `${dataString}callBack=${callBack}`;
      if (data) {
        Object.keys(data).forEach((item) => {
          url += `&${item}=${data[item]}`;
        });
      }
      const jsNode = document.createElement('script');
      jsNode.src = url;
      window[callBack] = (result) => {
        if (result) {
          reslove(result);
        } else {
          reject('没有数据');
        }
        document.body.removeChild(jsNode);
      };
      document.body.appendChild(jsNode);
    });
  },
};
